package com.hly.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hly.common.utils.PageUtils;
import com.hly.common.utils.Query;
import com.hly.product.dao.AttrGroupDao;
import com.hly.product.entity.*;
import com.hly.product.service.*;
import com.hly.product.vo.AttrGroupVo;
import com.hly.product.vo.AttrValues;
import com.hly.product.vo.EditableTabs;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private CategoryService categoryService;

    //查询所有
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        String cateLogId = (String) params.get("cateLogId");
        if(StringUtils.isNotEmpty(cateLogId)){
            wrapper.eq("catelog_id",cateLogId);
        }
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                wrapper
        );
        //根据sort字段排序
        List<AttrGroupEntity> collect = page.getRecords().stream().sorted((menu1, menu2) -> (menu2.getSort() == null ? 0 : menu2.getSort())-(menu1.getSort() == null ? 0 : menu1.getSort())).collect(Collectors.toList());
        page.setRecords(collect);
        return new PageUtils(page);
    }

    /**
     * spu规格维护，根据商品id获取所有分组的基本属性
     * @param spuId
     * @return
     */
    @Override
    public List<EditableTabs> getEditableTabsBySpuId(Long spuId) {
        //填充分组信息
        List<EditableTabs> collect = this.list().stream().map(item -> {
            EditableTabs tabs = new EditableTabs();
            tabs.setAttrGroupId(item.getAttrGroupId());
            tabs.setAttrGroupName(item.getAttrGroupName());
            return tabs;
        }).collect(Collectors.toList());


        collect = collect.stream().map(item -> {
            ArrayList<Long> ids = new ArrayList<>();
            //一个分组的所有属性id
            attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",item.getAttrGroupId())).stream()
                    .forEach(i -> {
                        ids.add(i.getAttrId());
                    });
            Long[] longs = ids.toArray(new Long[ids.size()]);

            //获取EditableTas类中 List<AttrValues> attrValues; 字段的值
            List<AttrValues> attrValuesList = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().and(i -> i.in("attr_id", longs).eq("spu_id", spuId))).stream().map(i -> {
                AttrValues attrValues = new AttrValues();
                //获取AttrValues类中 private List<AttrValue> attrValues; 字段的值
                AttrEntity byId = attrService.getById(i.getAttrId());
                BeanUtils.copyProperties(byId,attrValues);

                attrValues.setAttrValue(i.getAttrValue());
                attrValues.setShowDesc(i.getQuickShow().toString());
                attrValues.setId(i.getId());


                return attrValues;
            }).collect(Collectors.toList());

            //设置attrs
            item.setAttrs(attrValuesList);
            return item;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 根据分类id 获取所有分组以及所属分组的所有基本属性
     * @return
     */
    @Override
    public List<EditableTabs> getEditableTabsList(Map<String, Object> params) {
        String catelogId = (String) params.get("catelogId");
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(catelogId)){
            wrapper.eq("catelog_id",catelogId);
        }
        //填充分组信息
        List<EditableTabs> editableTabsList = this.list(wrapper).stream().map(item -> {
            EditableTabs tabs = new EditableTabs();
            BeanUtils.copyProperties(item,tabs);
            return tabs;
        }).collect(Collectors.toList());

        editableTabsList = editableTabsList.stream().map(editableTabs -> {
            List<Long> attrIds = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", editableTabs.getAttrGroupId())).stream().map(attrAttrGroupRelationEntity -> attrAttrGroupRelationEntity.getAttrId()).collect(Collectors.toList());
            List<AttrValues> attrValuesList = attrService.list(new QueryWrapper<AttrEntity>().in("attr_id", attrIds)).stream().map(attrEntity -> {
                AttrValues attrValues = new AttrValues();
                BeanUtils.copyProperties(attrEntity,attrValues);

                return attrValues;
            }).collect(Collectors.toList());
            editableTabs.setAttrs(attrValuesList);
            return editableTabs;
        }).collect(Collectors.toList());

        return editableTabsList;
    }

    /**
     * 获取所有分组信息，填充分类name
     * @param cateGoryId
     * @param params
     * @return
     */
    @Override
    public PageUtils queryAttrGroupPage(Long cateGoryId, Map<String, Object> params) {
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(cateGoryId != null && cateGoryId != 0){
            wrapper.eq("catelog_id",cateGoryId);
        }
        if(StringUtils.isNotEmpty(key)){
            wrapper.and(i -> i.like("attr_group_id",key).or().like("attr_group_name",key));
        }
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrGroupVo> collect = page.getRecords().stream().map(attrGroupEntity -> {
            AttrGroupVo attrGroupVo = new AttrGroupVo();
            BeanUtils.copyProperties(attrGroupEntity,attrGroupVo);
            CategoryEntity byId = categoryService.getById(attrGroupEntity.getCatelogId());
            if (byId != null) {
                attrGroupVo.setCatelogName(byId.getName());
            }

            //设置分类路径
            Long[] path = categoryService.findCateLogPath(attrGroupVo.getCatelogId());
            attrGroupVo.setCateLogPath(path);
            return attrGroupVo;
        }).sorted((menu1, menu2) -> (menu2.getSort() == null ? 0 : menu2.getSort())-(menu1.getSort() == null ? 0 : menu1.getSort())).collect(Collectors.toList());

        pageUtils.setList(collect);
        return pageUtils;
    }

    /**
     * 根据分组id 获取基本属性类型
     * @param params
     * @return
     */
    @Override
    public List<AttrEntity> AssAttrPage(HashMap<String, Object> params) {
        String groupId = (String) params.get("groupId");
        List<Long> attrIdList = null;
        if(StringUtils.isNotEmpty(groupId)){
            attrIdList = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", groupId)).stream().map(attrAttrgroupRelationEntity -> attrAttrgroupRelationEntity.getAttrId()).collect(Collectors.toList());
        }
        if(attrIdList.size() != 0){
            return attrService.list(new QueryWrapper<AttrEntity>().in("attr_id", attrIdList));
        }else {
            return null;
        }

    }

    /**
     * 删除，同时删除关联表中的内容
     * @param asList
     */
    @Transactional
    @Override
    public void removeAssByIds(List<Long> asList) {
        if(attrAttrgroupRelationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id",asList)) != 0){
            attrAttrgroupRelationService.remove(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id",asList));
        }
        this.removeByIds(asList);
    }

}